#!/bin/bash

script_dir=$(dirname $(realpath $0))
source "${script_dir}/check-toolchain"
source "${script_dir}/config"

echo -e "\033[42m\t\tBuild u-boot image\033[0m"
echo "tmpdir directory: ${tmpdir}"

image="${tmpdir}/u-boot.img"
p1="${tmpdir}/p1"
p2="${tmpdir}/p2"

check-toolchain gdisk

if [ -f $image ]; then
    echo "remove old image: $image"
    rm $image
fi

if [ -d $p1 ] ; then
    rm $p1 -rf
fi

if [ -d $p2 ] ; then
    sudo rm $p2 -rf
fi


# 创建空的镜像
dd if=/dev/zero of=$image bs=1M count=64

#创建GPT分区，一个用来存放kernel和设备树，另一个存放根文件系统
sgdisk -n 0:0:+12M -c 0:kernel $image
sgdisk -n 0:0:0 -c 0:rootfs $image

#查看分区
sgdisk -p $image

#寻找一个空闲的loop设备
loop=$(losetup -f)

echo "loop device: $loop"

#将SD卡镜像映射到loop设备上
echo "losetup $loop $image"
sudo losetup $loop $image

# 重新读取分区表
echo "partprobe $loop"
sudo partprobe $loop


#格式化
sudo mkfs.ext4 "${loop}p1"
sudo mkfs.ext4 "${loop}p2"

echo ""
echo ""

if [ ! -d $p1 ]; then
    mkdir $p1
fi

if [ ! -d $p2 ]; then
    mkdir $p2
fi

#挂载
sudo mount -t ext4 "${loop}p1" $p1
sudo mount -t ext4 "${loop}p2" $p2

#拷贝文件并制作根文件系统
sudo cp "${linux}/arch/arm/boot/zImage" $p1
sudo cp "${uboot}/arch/arm/dts/vexpress-v2p-ca9.dtb" $p1


echo "copy busybox: cp ${busybox}/_install/* $p2 -rap"
sudo cp $busybox/_install/* $p2 -rap

echo "copy compiler libs: cp ${gccdir}/lib/*  ${p2}/lib"

if [ ! -d $p2/lib ]; then
    sudo mkdir $p2/lib
fi
sudo cp $gccdir/lib/* $p2/lib -rap

echo "create dev directory"

#创建4个tty设备（c代表字符设备，4是主设备号，1~4分别是次设备号）
sudo mkdir -p "${p2}/dev"
sudo mknod "${p2}/dev/tty1" c 4 1
sudo mknod "${p2}/dev/tty2" c 4 2
sudo mknod "${p2}/dev/tty3" c 4 3
sudo mknod "${p2}/dev/tty4" c 4 4

#创建终端和回收站
sudo mknod -m 666 "${p2}/console" c 5 1
sudo mknod -m 666 "${p2}/null" c 1 3

# /etc/init.d/rcS 
sudo mkdir "${p2}/etc"
sudo mkdir "${p2}/etc/init.d"
sudo cp "${script_dir}/rcS" "${p2}/etc/init.d/rcS"
sudo chmod +x "${p2}/etc/init.d/rcS"

# #卸载
echo "sudo umount $p1"
sudo umount $p1

echo "sudo umount $p2"
sudo umount $p2

echo "sudo losetup -d $loop"
sudo losetup -d $loop
